package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.BehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: Luo Zeqi
 * @Date: 2022/11/16/23:30
 */

@Service
@Slf4j
public class BehaviorServiceImpl implements BehaviorService {

    @Autowired
    private CacheService cacheService;

    /**
     * 点赞/取消赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto dto) {
        try {
            String key = "LIKE_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/; //后段测试已通，需放开后联调
            String hashkey = String.valueOf(dto.getArticleId());
            if (dto.getOperation() == 0){
                //当前用户id+行为类型作为key、文章id作为hashkey,dto作为value
                String jsonString = JSON.toJSONString(dto);

                Boolean flag = cacheService.hPutIfAbsent(key, hashkey, jsonString);

            } else if (dto.getOperation() == 1){
                //取消点赞

                Long aLong = cacheService.hDelete(key, hashkey);
            }
        } catch (Exception e) {
            log.info("赞操作失败：{}", e);
            return ResponseResult.errorResult(500, "操作失败");
        }

        return ResponseResult.okResult("操作成功");
    }


    /**
     * 增加阅读次数
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        try {
            if (dto.getCount() == 1){
                //当前用户id+行为类型作为key、文章id作为hashkey,dto作为value
                String key = "READ_BEHAVIOR_" /*+  ApUserThreadLocalUtil.get().getId().intValue()*/;
                String hashkey = String.valueOf(dto.getArticleId());
                String jsonString = JSON.toJSONString(dto);
                //判断是否是第一次阅读
                boolean flag = cacheService.hExists(key, hashkey);
                if (!flag){
                    //不存在
                    cacheService.hPut(key, hashkey, jsonString);
                }else {
                    //存在，则阅读次数加一
                    String jsonStr = (String) cacheService.hGet(key, hashkey);
                    ReadBehaviorDto readBehaviorDto = JSON.parseObject(jsonStr, ReadBehaviorDto.class);
                    readBehaviorDto.setCount(readBehaviorDto.getCount() + dto.getCount());
                    String toJSONString = JSON.toJSONString(readBehaviorDto);

                    //更新
                    cacheService.hPut(key, hashkey, toJSONString);
                }

            } else {
                throw new CustomException(AppHttpCodeEnum.PARAM_INVALID); //参数有误
            }
        } catch (Exception e) {
            log.info("阅读次数+1操作失败：{}", e);
            return ResponseResult.errorResult(500, "操作失败");
        }

        return ResponseResult.okResult("操作成功");
    }


    /**
     * 不喜欢/取消
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLikesBehavior(UnLikesBehaviorDto dto) {
        try {
            String key = "UN_LIKE_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/; //后段测试已通，需放开后联调
            String hashkey = String.valueOf(dto.getArticleId());
            if (dto.getType() == 0){
                //当前用户id+行为类型作为key、文章id作为hashkey,dto作为value
                String jsonString = JSON.toJSONString(dto);

                cacheService.hPutIfAbsent(key, hashkey, jsonString);

            } else if (dto.getType() == 1){
                //取消不喜欢

                cacheService.hDelete(key, hashkey);
            }
        } catch (Exception e) {
            log.info("不喜欢操作失败：{}", e);
            return ResponseResult.errorResult(500, "操作失败");
        }

        return ResponseResult.okResult("操作成功");
    }
}
